﻿using Leeder.Logger;
using LeederHttp;
using LeederSerialPort;
using LogisticsAndong.Comm;
using LogisticsAndong.Handle;
using LogisticsAndong.Model;
using LogisticsAndong.Request;
using LogisticsAndong.Response;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TitaniumAS.Opc.Client.Common;
using TitaniumAS.Opc.Client.Da;

namespace LogisticsAndong.Business
{
    public class LogisticsAndongBusiness
    {
        /// <summary>
        /// 顺引顺建特殊工程过点信息监控
        /// </summary>
        public CancellationTokenSource cancel_specialProject;

        /// <summary>
        /// 主要设备监控线程
        /// </summary>
        public CancellationTokenSource cancel_mainequip;
        /// <summary>
        /// 车型集合
        /// </summary>
        List<CarModelModel> carModelList;

        /// <summary>
        /// 日志
        /// </summary>
        public LogOperate LogObj => Log.GetLogger(this.GetType());

        private MaterialDirectionBLL bllMaterialDirection;
        private PassPointSignalBLL bllPassPointSignal;
        private SystemDeviceMonitorBLL bllSystemDeviceMonitor;
        private SerialPortConfBLL bllSerialPortConf;
        private OpcBusiness opcBusiness = new OpcBusiness();

        /// <summary>
        /// 定义ups服务变量
        /// </summary>
        private UpsHandle upsServer;

        /// <summary>
        /// 用于判断是否首次进入线程（是否重启软件）
        /// </summary>
        private bool isServerStartUp = true;

        public delegate void ChangeDelegate();
        public event ChangeDelegate LipChangeEvent;
        public event ChangeDelegate LsdChangeEvent;

        private LogisticsAndongBusiness() { }
        private static LogisticsAndongBusiness _LogisticsAndongBusiness = null;
        public static LogisticsAndongBusiness CreateInstance()
        {
            if (_LogisticsAndongBusiness == null)
            {
                _LogisticsAndongBusiness = new LogisticsAndongBusiness();
            }
            return _LogisticsAndongBusiness;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            InitData();
            InitOpcDaServer();
            InitTask();
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void InitData()
        {
            bllMaterialDirection = new MaterialDirectionBLL();
            bllPassPointSignal = new PassPointSignalBLL();
            bllSystemDeviceMonitor = new SystemDeviceMonitorBLL();
            bllSerialPortConf = new SerialPortConfBLL();

            SignalLampDirectionBLL bllSignalLampDirection = new SignalLampDirectionBLL();
            UnpackingDirectionBLL bllUnpackingDirection = new UnpackingDirectionBLL();
            SystemDeviceBLL bllSystemDevice = new SystemDeviceBLL();
            CarModelBLL bllCarModel = new CarModelBLL();

            //从数据库中取出系统需要的数据
            List<MaterialDirectionModel> materialDirectionList = bllMaterialDirection.GetModelList();
            List<SignalLampDirectionModel> signalLampDirectionList = bllSignalLampDirection.GetModelList();
            List<UnpackingDirectionModel> unpackingDirectionList = bllUnpackingDirection.GetModelList();
            List<SystemDeviceModel> systemDeviceList = bllSystemDevice.GetModelList();
            carModelList = bllCarModel.GetModelList();

            //初始化全局变量
            GolbalVariable.MaterialDirectionBag = new ConcurrentBag<MaterialDirectionModel>(materialDirectionList);
            GolbalVariable.SignalLampDirectionBag = new ConcurrentBag<SignalLampDirectionModel>(signalLampDirectionList);
            GolbalVariable.UnpackingDirectionBag = new ConcurrentBag<UnpackingDirectionModel>(unpackingDirectionList);
            GolbalVariable.SystemDeviceBag = new ConcurrentBag<SystemDeviceModel>(systemDeviceList);
            GolbalVariable.SignalLampBlinkThreadDictionary = new ConcurrentDictionary<string, Thread>();
            GolbalVariable.SignalLampShowModelBag = new ConcurrentBag<SignalLampShowModel>();
            GolbalVariable.UnpackingDirectionModelBag = new ConcurrentBag<UnpackingDirectionShowModel>();
            GolbalVariable.OpcHelper = new OpcHelper();
            GolbalVariable.CurrentParamet = new CurrentParameter();
            GolbalVariable.OpcDaGroupList = new List<OpcDaGroup>();
            GolbalVariable.UpsStatus = new UpsModel();
            GolbalVariable.PicsState = true;
            GolbalVariable.LipState = true;
            GolbalVariable.PlcState = true;

            CurrentParameter currentParamet = new CurrentParameter();
            //GolbalVariable.SerialPortConf = bllSerialPortConf.DisposalData(ref currentParamet);
            GolbalVariable.CurrentParamet = currentParamet;

            //初始化全局变量
            foreach (var signalLamp in signalLampDirectionList)
            {
                var unpacking = unpackingDirectionList.Where(p => p.ID == signalLamp.UnpackingId).FirstOrDefault();
                if (unpacking != null)
                {
                    SignalLampShowModel model = new SignalLampShowModel
                    {
                        Id = signalLamp.ID,
                        LampId = signalLamp.ID,
                        PullingRopeName = signalLamp.LampName,
                        ChainMark = signalLamp.ChainMark,
                        PullingRopeInAddress = signalLamp.ControlInputAddress,
                        GreenOutAddress = signalLamp.GreenOutputAddress,
                        RedOutAddress = signalLamp.RedOutputAddress,
                        TypeId = signalLamp.TypeId
                    };
                    GolbalVariable.SignalLampShowModelBag.Add(model);
                }
            }

            //初始化全局变量
            foreach (var unpacking in unpackingDirectionList)
            {
                UnpackingDirectionShowModel model = new UnpackingDirectionShowModel
                {
                    Id = unpacking.ID,
                    UnpackingId = unpacking.ID,
                    UnpackingName = unpacking.UnpackingName,
                    DataType = unpacking.DataType,
                    IpAddress = unpacking.IpAddress,
                    SignalMark = unpacking.SignalMark,
                    ControlName = unpacking.ControlName
                };
                GolbalVariable.UnpackingDirectionModelBag.Add(model);
            }
        }

        /// <summary>
        /// 初始化OpcServer
        /// </summary>
        private void InitOpcDaServer()
        {
            OpcConnectBLL bllOpcConnect = new OpcConnectBLL();
            OpcDeviceBLL bllOpcDevice = new OpcDeviceBLL();
            OpcGroupBLL bllOpcGroup = new OpcGroupBLL();
            OpcTagBLL bllOpcTag = new OpcTagBLL();

            //获取OPC的 连接 组 TAG
            OpcConnectModel opcConnect = bllOpcConnect.GetModel();
            List<OpcDeviceModel> opcDeviceList = bllOpcDevice.GetModelList();
            List<OpcGroupModel> opcGroupList = bllOpcGroup.GetModelList();
            List<OpcTagModel> opcTagList = bllOpcTag.GetModelList();
            GolbalVariable.OpcTagBag = new ConcurrentBag<OpcTagModel>(opcTagList);
            GolbalVariable.opcGroupList = opcGroupList;

            //绑定LIP触发事件
            opcBusiness.LipChangeEvent += LipChange_Event;
            opcBusiness.LsdChangeEvent += LsdChange_Event;

            Thread thread = new Thread(Delay);
            thread.Start();

            try
            {
                //获取服务名称，并创建URL
                Uri uri = UrlBuilder.Build(opcConnect.OpcServerProgId);
                GolbalVariable.OpcHelper.opcServer = new OpcDaServer(uri);
                //绑定事件，并且启动OPC重连线程
                GolbalVariable.OpcHelper.opcServer.ConnectionStateChanged += GolbalVariable.OpcHelper.Server_ConnectionStateChanged;
                GolbalVariable.OpcHelper.opcServer.Shutdown += GolbalVariable.OpcHelper.Server_Shutdown;
                GolbalVariable.OpcHelper.opcServer.Connect();

                //依次遍历opcDevices->opcGroups->opcTags，创建OPC分组，并绑定ValuesChanged事件
                var opcDevices = opcDeviceList.Where(p => p.ConnectId == opcConnect.ID);
                foreach (var opcDevice in opcDevices)
                {
                    var opcGroups = opcGroupList.Where(p => p.DeviceId == opcDevice.ID);
                    foreach (var opcGroup in opcGroups)
                    {
                        OpcDaGroup opcDaGroup = GolbalVariable.OpcHelper.opcServer.AddGroup(opcGroup.GroupName);
                        List<OpcDaItemDefinition> list = new List<OpcDaItemDefinition>();
                        var opcTags = opcTagList.Where(p => p.GroupId == opcGroup.ID);
                        if (opcTags.Count() == 0) continue;
                        foreach (var opcTag in opcTags)
                        {
                            if (string.IsNullOrEmpty(opcTag.TagName))
                                continue;
                            string ItemId = opcDevice.DeviceName + "." + opcGroup.GroupName + "." + opcTag.TagName;
                            list.Add(new OpcDaItemDefinition { ItemId = ItemId, IsActive = true });
                            opcTag.TagName = ItemId;
                        }
                        var results = opcDaGroup.AddItems(list);
                        opcDaGroup.UpdateRate = TimeSpan.FromMilliseconds(opcGroup.UpdateRate);
                        //根据组名分别订阅不同的逻辑事件
                        switch (opcGroup.GroupName)
                        {
                            case "LIP":
                                opcDaGroup.ValuesChanged += OpcLipGroup_ValuesChanged;  //绑定ValuesChanged事件
                                break;
                            case "LSD":
                                opcDaGroup.ValuesChanged += OpcLsdGroup_ValuesChanged;  //绑定ValuesChanged事件
                                break;
                            case "KK":
                                opcDaGroup.ValuesChanged += OpcKkGroup_ValuesChanged;  //绑定ValuesChanged事件
                                break;
                            case "SBJK":
                                opcDaGroup.ValuesChanged += OpcSbjkGroup_ValuesChanged;  //绑定ValuesChanged事件
                                break;
                            case "PICS":
                                opcDaGroup.ValuesChanged += OpcPicsGroup_ValuesChanged;  //绑定ValuesChanged事件
                                break;
                            case "LSZT":
                                opcDaGroup.ValuesChanged += OpcLsztGroup_ValuesChanged;  //绑定ValuesChanged事件
                                break;
                        }

                        opcDaGroup.IsActive = true;
                        opcDaGroup.IsSubscribed = true;
                        GolbalVariable.OpcDaGroupList.Add(opcDaGroup);
                        //记录错误信息.
                        foreach (OpcDaItemResult result in results)
                        {
                            if (result.Error.Failed)
                                LogObj.Error(result.Item == null ? "" : result.Item.ItemId + " 变量错误，请核对变量名称");                            
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogObj.Error(ex.Message);
            }
        }

        /// <summary>
        /// 初始化线程
        /// </summary>
        private void InitTask()
        {
            //主要设备监控线程
            if (GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "IP").Any())
            {
                cancel_mainequip = new CancellationTokenSource();
                LogObj.Info("开启主要设备监控线程启动");
                Task.Factory.StartNew(() =>
                {
                    BindMainPower();
                }, cancel_mainequip.Token);
            }
            //API数据获取扣减线程
            if (GolbalVariable.MaterialDirectionBag.Where(x => x.DataSource == "API").Any())
            {
                cancel_specialProject = new CancellationTokenSource();
                LogObj.Info("顺引顺建特殊工程过点信息监控");
                Task.Factory.StartNew(() =>
                {
                    GetPassPointData();
                }, cancel_specialProject.Token);
            }

            //创建ups监控对象的实例
            upsServer = new UpsHandle();
            //接收数据事件
            upsServer.Received += UpsServer_Received;
            //初始化com口
            LogObj.Info("ups监控线程开启");
            upsServer.InitCom();
        }

        /// <summary>
        /// 软件启动后LIP组数据延迟3秒再处理，过滤异常数据
        /// </summary>
        private void Delay()
        {
            Thread.Sleep(3000);
            isServerStartUp = false;
        }

        /// <summary>
        /// OPC-Lip组订阅事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpcLipGroup_ValuesChanged(object sender, OpcDaItemValuesChangedEventArgs e)
        {
            try
            {
                foreach (OpcDaItemValue value in e.Values)
                {
                    if (value == null || value.Value == null)
                        continue;

                    var info = GolbalVariable.OpcTagBag.Where(x => x.TagName == value.Item.ItemId).FirstOrDefault();
                    if (info != null)
                    {
                        int result = 0;
                        //判断OPC值类型并统一转换为INT类型（BOOL类型true=1，false=0）
                        if (value.Value is bool)
                            result = (Convert.ToBoolean(value.Value) ? 1 : 0);
                        else
                            int.TryParse(value.Value.ToString(), out result);
                        //result==1时为过点信息,result==0时不作处理
                        if (result == 0)
                            continue;
                        //业务处理
                        if (!isServerStartUp)
                            opcBusiness.LipGroup(info, result);
                    }

                }
            }
            catch (Exception ex)
            {
                LogObj.Error(ex.Message);
            }
        }

        /// <summary>
        /// OPC-Lsd组订阅事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpcLsdGroup_ValuesChanged(object sender, OpcDaItemValuesChangedEventArgs e)
        {
            try
            {
                foreach (OpcDaItemValue value in e.Values)
                {
                    if (value == null || value.Value == null)
                        continue;
                    var info = GolbalVariable.OpcTagBag.Where(x => x.TagName == value.Item.ItemId).FirstOrDefault();
                    if (info != null)
                    {
                        int result = 0;
                        //判断OPC值类型并统一转换为INT类型（BOOL类型true=1，false=0）
                        if (value.Value is bool)
                            result = (Convert.ToBoolean(value.Value) ? 1 : 0);
                        else
                            int.TryParse(value.Value.ToString(), out result);
                        //业务处理
                        opcBusiness.LsdGroup(info, result);
                    }
                }
            }
            catch (Exception ex)
            {
                LogObj.Error(ex.Message);
            }
        }

        /// <summary>
        /// OPC-Kk组订阅事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpcKkGroup_ValuesChanged(object sender, OpcDaItemValuesChangedEventArgs e)
        {
            try
            {
                foreach (OpcDaItemValue value in e.Values)
                {
                    if (value == null || value.Value == null)
                        continue;
                    var info = GolbalVariable.OpcTagBag.Where(x => x.TagName == value.Item.ItemId).FirstOrDefault();
                    if (info != null)
                    {
                        int result = 0;
                        //判断OPC值类型并统一转换为INT类型（BOOL类型true=1，false=0）
                        if (value.Value is bool)
                            result = (Convert.ToBoolean(value.Value) ? 1 : 0);
                        else
                            int.TryParse(value.Value.ToString(), out result);
                        //业务处理
                        opcBusiness.KkGroup(info, result);
                    }
                }
            }
            catch (Exception ex)
            {
                LogObj.Error(ex.Message);
            }
        }

        /// <summary>
        /// OPC-Lszt组订阅事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpcLsztGroup_ValuesChanged(object sender, OpcDaItemValuesChangedEventArgs e)
        {
            try
            {
                foreach (OpcDaItemValue value in e.Values)
                {
                    if (value == null || value.Value == null)
                        continue;
                    var info = GolbalVariable.OpcTagBag.Where(x => x.TagName == value.Item.ItemId).FirstOrDefault();
                    if (info != null)
                    {
                        int result = 0;
                        //判断OPC值类型并统一转换为INT类型（BOOL类型true=1，false=0）
                        if (value.Value is bool)
                            result = (Convert.ToBoolean(value.Value) ? 1 : 0);
                        else
                            int.TryParse(value.Value.ToString(), out result);
                        //result==1时为过点信息,result==0时不作处理
                        if (result == 0)
                            continue;
                        //业务处理
                        opcBusiness.LsztGroup(info, result);
                    }
                }
            }
            catch (Exception ex)
            {
                LogObj.Error(ex.Message);
            }
        }

        /// <summary>
        /// OPC-Sbjk组订阅事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpcSbjkGroup_ValuesChanged(object sender, OpcDaItemValuesChangedEventArgs e)
        {
            try
            {
                foreach (OpcDaItemValue value in e.Values)
                {
                    if (value == null || value.Value == null)
                        continue;
                    var info = GolbalVariable.OpcTagBag.Where(x => x.TagName == value.Item.ItemId).FirstOrDefault();
                    if (info != null)
                    {
                        int result = 0;
                        //判断OPC值类型并统一转换为INT类型（BOOL类型true=1，false=0）
                        if (value.Value is bool)
                            result = (Convert.ToBoolean(value.Value) ? 1 : 0);
                        else
                            int.TryParse(value.Value.ToString(), out result);
                        //业务处理
                        opcBusiness.SbjkGroup(info, result);
                    }
                }
            }
            catch (Exception ex)
            {
                LogObj.Error(ex.Message);
            }
        }

        /// <summary>
        /// OPC-Pics组订阅事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpcPicsGroup_ValuesChanged(object sender, OpcDaItemValuesChangedEventArgs e)
        {
            try
            {
                foreach (OpcDaItemValue value in e.Values)
                {
                    if (value == null || value.Value == null)
                        continue;
                    var info = GolbalVariable.OpcTagBag.Where(x => x.TagName == value.Item.ItemId).FirstOrDefault();
                    if (info != null)
                    {
                        int result = 0;
                        //判断OPC值类型并统一转换为INT类型（BOOL类型true=1，false=0）
                        if (value.Value is bool)
                            result = (Convert.ToBoolean(value.Value) ? 1 : 0);
                        else
                            int.TryParse(value.Value.ToString(), out result);
                        //业务处理
                        opcBusiness.PicsGroup(info, result);
                    }
                }
            }
            catch (Exception ex)
            {
                LogObj.Error(ex.Message);
            }
        }

        private bool picsStatus = true;
        private bool plcStatus = true;
        private bool lipStatus = true;
        /// <summary>
        /// 绑定硬件设备
        /// </summary>
        private async void BindMainPower()
        {
            string plcIp = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "IP" && x.DeviceName == "PLC").FirstOrDefault().DeviceIpAddress;
            string lipIp = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "IP" && x.DeviceName == "LIP").FirstOrDefault().DeviceIpAddress;
            string picsIp = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "IP" && x.DeviceName == "PICS").FirstOrDefault().DeviceIpAddress;
            while (true)
            {
                if (cancel_mainequip.Token.IsCancellationRequested)
                {
                    cancel_mainequip.Dispose();
                    break;
                }
                plcStatus = PublicHelper.PingIp(plcIp);
                lipStatus = PublicHelper.PingIp(lipIp);
                picsStatus = PublicHelper.PingIp(picsIp);
                if(!plcStatus && GolbalVariable.PlcState != false)
                {
                    SystemDeviceMonitorModel model = new SystemDeviceMonitorModel()
                    {
                        ID = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "IP" && x.DeviceName == "PLC").FirstOrDefault().ID,
                        DeviceName = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "IP" && x.DeviceName == "PLC").FirstOrDefault().DeviceName,
                        ExceptionDescription = "设备通讯异常",
                        ExceptionDate = DateTime.Now
                    };
                    //NLoggerHelper.INFO("设备异常(" + x.device_name + ")");
                    bllSystemDeviceMonitor.Add(model);
                    GolbalVariable.PlcState = false;
                }else
                { GolbalVariable.PlcState = plcStatus; }
                if (!lipStatus && GolbalVariable.LipState != false)
                {
                    SystemDeviceMonitorModel model = new SystemDeviceMonitorModel()
                    {
                        ID = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "IP" && x.DeviceName == "LIP").FirstOrDefault().ID,
                        DeviceName = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "IP" && x.DeviceName == "LIP").FirstOrDefault().DeviceName,
                        ExceptionDescription = "设备通讯异常",
                        ExceptionDate = DateTime.Now
                    };
                    //NLoggerHelper.INFO("设备异常(" + x.device_name + ")");
                    bllSystemDeviceMonitor.Add(model);
                    GolbalVariable.LipState = false;
                }
                else
                { GolbalVariable.LipState = lipStatus; }
                if (!picsStatus && GolbalVariable.PicsState != false)
                {
                    SystemDeviceMonitorModel model = new SystemDeviceMonitorModel()
                    {
                        ID = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "IP" && x.DeviceName == "PICS").FirstOrDefault().ID,
                        DeviceName = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "IP" && x.DeviceName == "PICS").FirstOrDefault().DeviceName,
                        ExceptionDescription = "设备通讯异常",
                        ExceptionDate = DateTime.Now
                    };
                    //NLoggerHelper.INFO("设备异常(" + x.device_name + ")");
                    bllSystemDeviceMonitor.Add(model);
                    GolbalVariable.PicsState = false;
                }
                else
                { GolbalVariable.PicsState = picsStatus; }
                await Task.Delay(5000);
            }
        }

        int SpecialCarIndex = 81; //特殊车型截取起始位置
        int SpecialCarLength = 1; //特殊车型截长度

        /// <summary>
        /// 获取过点数据
        /// </summary>
        private async void GetPassPointData()
        {
            while (!cancel_specialProject.Token.IsCancellationRequested)
            {
                try
                {
                    foreach (var item in GolbalVariable.MaterialDirectionBag.Where(x=> x.DataSource == "API"))
                    {
                        if (item.LineId != 0 && item.StationId != 0)
                        {
                            var result = GetSpecialProjectPass(item);
                            if (result != null)
                            {
                                if (!string.IsNullOrEmpty(result.BCData))
                                {
                                    if ((SpecialCarIndex + SpecialCarLength) > result.BCData.Length)
                                        continue;
                                    //从部品实体中提取特殊部品车型标识
                                    var marks1 = item.CarMark.Split(',');
                                    //取result的第几位数据,判断是否包含在顺引顺建的配置当中
                                    var markChar = result.BCData.Substring(SpecialCarIndex, SpecialCarLength);
                                    var listModel = carModelList.Where(x=>x.CarModelGroup == 1);
                                    ///根据车型名称对应记号
                                    List<string> listMark = new List<string>();
                                    foreach (var name in marks1)
                                    {
                                        //判断本地是否设置了对应车型，有则加入listMark集合待下一步处理
                                        var model = listModel.Where(x => x.CarModelName == name).FirstOrDefault();
                                        if (model != null)
                                            listMark.Add(model.Line);
                                    }
                                    var marks = listMark.ToArray();
                                    //判断是否包含在顺引顺建的配置当中
                                    if (marks.Contains(markChar))
                                    {
                                        //逻辑方法
                                        bool flag = false;
                                        PassPointSignalModel info = new PassPointSignalModel();

                                        string bodyNum = result.BCData.Substring(5, 5);
                                        if (bllPassPointSignal.CheckSpecialPassPointSignal(item.ID, bodyNum))
                                        {
                                            continue;
                                        }
                                        flag = true;
                                        //更新过点数据
                                        info.CurrentBodyNo = bodyNum;
                                        info.CreateTime = DateTime.Now;
                                        info.IndexId = item.ID;

                                        if (flag == true)
                                        {
                                            int left_count = item.LeftCount;
                                            CalculationHelper.Subtraction(ref left_count, 1);
                                            CalculationHelper.CustomOperation(ref left_count, 3, 1, item.OnceTransportCount);
                                            item.LeftCount = left_count;
                                            //把运算后的部品实体更新到数据库
                                            bllMaterialDirection.Update(item);
                                            //更新到数据库
                                            bllPassPointSignal.Add(info);
                                            //保存扣减数量日志
                                            LogObj.Info("调用API接口剩余台数扣减(" + item.MaterialName + ":" + item.LeftCount + ")");
                                        }
                                    }
                                }
                            }
                        }
                        await Task.Delay(10000);
                    }
                }
                catch (Exception ex)
                {
                    LogObj.Error("特殊工程过载：" + ex.Message);
                }
                await Task.Delay(10000);
            }
        }

        /// <summary>
        /// 获取顺引顺建特殊工程
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public SpecialProjectResponse GetSpecialProjectPass(MaterialDirectionModel model)
        {
            if (model.LineId == 0 || model.StationId == 0)
                return null;
            SpecialProjectRequest request = new SpecialProjectRequest() { lineid = model.LineId.ToString(), position = model.StationId };
            var requestStr = JsonConvert.SerializeObject(request);
            var result = HttpHelper.RequestBody(model.SignalMark, "POST", requestStr);
            if (string.IsNullOrEmpty(result))
                return null;
            try
            {
                var response = JsonConvert.DeserializeObject<ReceiveResult>(result);
                if (response != null)
                    return response.data;
            }
            catch (Exception ex)
            {
                LogObj.Error(ex.Message);
            }
            return null;
        }

        /// <summary>
        /// UPS接收数据事件
        /// </summary>
        /// <param name="data"></param>
        private void UpsServer_Received(UpsModel data)
        {
            //把UPS当前状态更新到缓存中（用于界面状态的更新）
            GolbalVariable.UpsStatus = data;
            //数据处理
            UpsBusiness.CheckUps(data);
        }

        /// <summary>
        /// LIP触发事件
        /// </summary>
        private void LipChange_Event()
        {
            try
            {
                LipChangeEvent();
            }
            catch(Exception ex)
            { }
        }

        /// <summary>
        /// LSD触发事件
        /// </summary>
        private void LsdChange_Event()
        {
            try
            {
                LsdChangeEvent();
            }
            catch (Exception ex)
            { }
        }

    }
}
